<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Hexo, NexT" />








  <link rel="shortcut icon" type="image/x-icon" href="/blog/favicon.ico?v=5.1.2" />






<meta name="description" content="1. Web Worker 简介1.1. 什么是 Web WorkerWeb Worker 是 HTML5 标准的一部分，这一规范定义了一套 API，它允许一段 JavaScript 程序运行在主线程之外的另外一个线程中。工作线程允许开发人员编写能够长时间运行而不被用户所中断的后台程序， 去执行事务或者逻辑，并同时保证页面对用户的及时响应，可以将一些大量计算的代码交给 web worker 运行而">
<meta property="og:type" content="article">
<meta property="og:title" content="HTML5 之 Web Worker">
<meta property="og:url" content="http://xiezixi.oschina.io/2018/06/01/HTML5-WebWorker/index.html">
<meta property="og:site_name" content="个人博客">
<meta property="og:description" content="1. Web Worker 简介1.1. 什么是 Web WorkerWeb Worker 是 HTML5 标准的一部分，这一规范定义了一套 API，它允许一段 JavaScript 程序运行在主线程之外的另外一个线程中。工作线程允许开发人员编写能够长时间运行而不被用户所中断的后台程序， 去执行事务或者逻辑，并同时保证页面对用户的及时响应，可以将一些大量计算的代码交给 web worker 运行而">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://xiezixi.oschina.io/blog/images/webWorker1.png">
<meta property="og:updated_time" content="2018-06-01T08:53:48.102Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="HTML5 之 Web Worker">
<meta name="twitter:description" content="1. Web Worker 简介1.1. 什么是 Web WorkerWeb Worker 是 HTML5 标准的一部分，这一规范定义了一套 API，它允许一段 JavaScript 程序运行在主线程之外的另外一个线程中。工作线程允许开发人员编写能够长时间运行而不被用户所中断的后台程序， 去执行事务或者逻辑，并同时保证页面对用户的及时响应，可以将一些大量计算的代码交给 web worker 运行而">
<meta name="twitter:image" content="http://xiezixi.oschina.io/blog/images/webWorker1.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Muse',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://xiezixi.oschina.io/2018/06/01/HTML5-WebWorker/"/>





  <title>HTML5 之 Web Worker | 个人博客</title>
  














</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">
  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">个人博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">曦瓜皮</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>


 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://xiezixi.oschina.io/blog/2018/06/01/HTML5-WebWorker/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="曦瓜皮">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="个人博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">HTML5 之 Web Worker</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-06-01T16:53:48+08:00">
                2018-06-01
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/HTML5/" itemprop="url" rel="index">
                    <span itemprop="name">HTML5</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="1-Web-Worker-简介"><a href="#1-Web-Worker-简介" class="headerlink" title="1. Web Worker 简介"></a>1. Web Worker 简介</h2><h3 id="1-1-什么是-Web-Worker"><a href="#1-1-什么是-Web-Worker" class="headerlink" title="1.1. 什么是 Web Worker"></a>1.1. 什么是 Web Worker</h3><p>Web Worker 是 HTML5 标准的一部分，这一规范定义了一套 API，它允许一段 JavaScript 程序运行在主线程之外的另外一个线程中。工作线程允许开发人员编写能够长时间运行而不被用户所中断的后台程序， 去执行事务或者逻辑，并同时保证页面对用户的及时响应，可以将一些大量计算的代码交给 web worker 运行而不冻结用户界面。</p>
<h3 id="1-2-Web-Worker-问世背景"><a href="#1-2-Web-Worker-问世背景" class="headerlink" title="1.2. Web Worker 问世背景"></a>1.2. Web Worker 问世背景</h3><p>JavaScript 引擎是单线程运行的，JavaScript 中耗时的 I/O 操作都被处理为异步操作，它们包括键盘、鼠标 I/O 输入输出事件、窗口大小的 resize 事件、定时器(setTimeout、setInterval)事件、Ajax 请求网络 I/O回调等。当这些异步任务发生的时候，它们将会被放入浏览器的事件任务队列中去，等到JavaScript运行时执行线程空闲时候才会按照队列先进先出的原则被一一执行，但终究还是单线程。</p>
<p>很多人觉得异步（promise async/await），都是通过类似 event loop 在平常的工作中已经足够，但是如果做复杂运算，这些异步伪线程的不足就逐渐体现出来，比如 setTimeout 拿到的值并不正确，再者假如页面有复杂运算的时候页面很容易触发假死状态，为了有多线程功能，webworker 问世了。不过，这并不意味着 JavaScript 语言本身就支持了多线程，对于 JavaScript 语言本身它仍是运行在单线程上的， Web Worker 只是浏览器（宿主环境）提供的一个能力／API。</p>
<p><img src="http://xiezixi.oschina.io/blog/images/webWorker1.png" alt="JavaScript 事件机制"></p>
<h3 id="1-3-Web-Worker-类型"><a href="#1-3-Web-Worker-类型" class="headerlink" title="1.3. Web Worker 类型"></a>1.3. Web Worker 类型</h3><p>Web workers 可分为两种类型：专用线程 dedicated web worker，以及共享线程 shared web worker。Dedicated web worker 随当前页面的关闭而结束；这意味着Dedicated web worker 只能被创建它的页面访问。与之相对应的Shared web worker 可以被多个页面访问。在 Javascript 代码中，<code>Work</code>类型代表 Dedicated web worker，而<code>SharedWorker</code>类型代表 Shared web worker。<br>而 Shared Worker 则可以被多个页面所共享（同域情况下）。</p>
<h3 id="1-4-浏览器兼容性"><a href="#1-4-浏览器兼容性" class="headerlink" title="1.4. 浏览器兼容性"></a>1.4. 浏览器兼容性</h3><p><a href="https://caniuse.com/#search=Web%20Workers" target="_blank" rel="noopener">Web Worker 浏览器兼容性</a></p>
<h2 id="2-使用方法"><a href="#2-使用方法" class="headerlink" title="2. 使用方法"></a>2. 使用方法</h2><h3 id="2-1-创建-Web-Worker"><a href="#2-1-创建-Web-Worker" class="headerlink" title="2.1. 创建 Web Worker"></a>2.1. 创建 Web Worker</h3><p>Web Worker的创建是在主线程当中通过传入文件的url来实现的。如下所示：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> webWorker = <span class="keyword">new</span> Worker(<span class="string">"webWorker.js"</span>);</span><br></pre></td></tr></table></figure>
<h3 id="2-2-事件监听"><a href="#2-2-事件监听" class="headerlink" title="2.2. 事件监听"></a>2.2. 事件监听</h3><p>返回的是 webWorker 实例对象,该对象是主线程和其他线程的通讯桥梁<br>主线程和其他线程可以通过如下相关的API进行通讯 。</p>
<blockquote>
<p><code>onmessage</code>: 监听事件<br><code>postmessage</code>: 传送事件</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//主线程 main.js</span></span><br><span class="line"><span class="keyword">var</span> worker = <span class="keyword">new</span> Worker(<span class="string">"worker.js"</span>);</span><br><span class="line">worker.onmessage = <span class="function"><span class="keyword">function</span>(<span class="params">event</span>)</span>&#123;</span><br><span class="line">    <span class="comment">// 主线程收到子线程的消息</span></span><br><span class="line">&#125;;</span><br><span class="line"><span class="comment">// 主线程向子线程发送消息</span></span><br><span class="line">worker.postMessage(&#123;</span><br><span class="line">    type: <span class="string">"start"</span>,</span><br><span class="line">    value: <span class="number">12345</span></span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">//web worker.js</span></span><br><span class="line">onmessage = <span class="function"><span class="keyword">function</span>(<span class="params">event</span>)</span>&#123;</span><br><span class="line">   <span class="comment">// 收到</span></span><br><span class="line">&#125;;</span><br><span class="line">postMessage(&#123;</span><br><span class="line">    type: <span class="string">"debug"</span>,</span><br><span class="line">    message: <span class="string">"Starting processing..."</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<h3 id="2-3-终止-Web-Worker"><a href="#2-3-终止-Web-Worker" class="headerlink" title="2.3. 终止 Web Worker"></a>2.3. 终止 Web Worker</h3><p>如果在某个时机不想要 Worker 继续运行了，那么我们需要终止掉这个线程，可以调用 在主线程 worker 的 <code>terminate</code> 方法或者在相应的线程中调用 <code>close</code>：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 方式一 main.js 在主线程停止方式</span></span><br><span class="line"><span class="keyword">var</span> worker = <span class="keyword">new</span> Worker(<span class="string">'./worker.js'</span>);</span><br><span class="line">...</span><br><span class="line">worker.terminate();</span><br><span class="line"></span><br><span class="line"><span class="comment">// 方式二、worker.js</span></span><br><span class="line">self.close();</span><br></pre></td></tr></table></figure>
<h3 id="2-4-错误机制"><a href="#2-4-错误机制" class="headerlink" title="2.4. 错误机制"></a>2.4. 错误机制</h3><p>提供了<code>onerror</code> API</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">worker.addEventListener(<span class="string">'error'</span>, <span class="function"><span class="keyword">function</span> (<span class="params">e</span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'MAIN: '</span>, <span class="string">'ERROR'</span>, e);</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'filename:'</span> + e.filename + <span class="string">'-message:'</span> + e.message + <span class="string">'-lineno:'</span> + e.lineno);</span><br><span class="line">&#125;);</span><br><span class="line"><span class="comment">// event.filename: 导致错误的 Worker 脚本的名称；</span></span><br><span class="line"><span class="comment">// event.message: 错误的信息；</span></span><br><span class="line"><span class="comment">// event.lineno: 出现错误的行号；</span></span><br></pre></td></tr></table></figure>
<h3 id="2-5-简单实例"><a href="#2-5-简单实例" class="headerlink" title="2.5. 简单实例"></a>2.5. 简单实例</h3><h4 id="2-5-1-webWork-html"><a href="#2-5-1-webWork-html" class="headerlink" title="2.5.1 webWork.html"></a>2.5.1 webWork.html</h4><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE html&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">"utf-8"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>webWorker<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">p</span>&gt;</span>计数：</span><br><span class="line">    <span class="tag">&lt;<span class="name">output</span> <span class="attr">id</span>=<span class="string">"result"</span>&gt;</span><span class="tag">&lt;/<span class="name">output</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">button</span> <span class="attr">onclick</span>=<span class="string">"startWorker()"</span>&gt;</span>开始工作<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">button</span> <span class="attr">onclick</span>=<span class="string">"stopWorker()"</span>&gt;</span>停止工作<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="undefined"></span></span><br><span class="line"><span class="javascript">    <span class="keyword">var</span> webWorker;</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="javascript">    <span class="function"><span class="keyword">function</span> <span class="title">startWorker</span>(<span class="params"></span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">        <span class="keyword">if</span> (<span class="keyword">typeof</span>(Worker) !== <span class="string">"undefined"</span>) &#123;</span></span><br><span class="line"><span class="javascript">            <span class="keyword">if</span> (<span class="keyword">typeof</span>(webWorker) == <span class="string">"undefined"</span>) &#123;</span></span><br><span class="line"><span class="javascript">                webWorker = <span class="keyword">new</span> Worker(<span class="string">"webWorker.js"</span>);</span></span><br><span class="line"><span class="undefined">            &#125;</span></span><br><span class="line"><span class="javascript">            webWorker.onmessage = <span class="function"><span class="keyword">function</span> (<span class="params">event</span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">                <span class="built_in">document</span>.getElementById(<span class="string">"result"</span>).innerHTML = event.data;</span></span><br><span class="line"><span class="undefined">            &#125;;</span></span><br><span class="line"><span class="javascript">        &#125; <span class="keyword">else</span> &#123;</span></span><br><span class="line"><span class="javascript">            <span class="built_in">document</span>.getElementById(<span class="string">"result"</span>).innerHTML = <span class="string">"抱歉，你的浏览器不支持 Web Workers..."</span>;</span></span><br><span class="line"><span class="undefined">        &#125;</span></span><br><span class="line"><span class="undefined">    &#125;</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="javascript">    <span class="function"><span class="keyword">function</span> <span class="title">stopWorker</span>(<span class="params"></span>) </span>&#123;</span></span><br><span class="line"><span class="undefined">        webWorker.terminate();</span></span><br><span class="line"><span class="javascript">        webWorker = <span class="literal">undefined</span>;</span></span><br><span class="line"><span class="undefined">    &#125;</span></span><br><span class="line"><span class="undefined"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h4 id="2-5-2-webWork-js"><a href="#2-5-2-webWork-js" class="headerlink" title="2.5.2 webWork.js"></a>2.5.2 webWork.js</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> i=<span class="number">0</span>;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">timedCount</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    i=i+<span class="number">1</span>;</span><br><span class="line">    postMessage(i);</span><br><span class="line">    setTimeout(<span class="string">"timedCount()"</span>,<span class="number">500</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">timedCount();</span><br></pre></td></tr></table></figure>
<h2 id="3-sharedWorker"><a href="#3-sharedWorker" class="headerlink" title="3. sharedWorker"></a>3. sharedWorker</h2><h3 id="3-1-sharedWorker-介绍"><a href="#3-1-sharedWorker-介绍" class="headerlink" title="3.1. sharedWorker 介绍"></a>3.1. sharedWorker 介绍</h3><p>对于 Web Worker ，一个 tab 页面只能对应一个 Worker 线程，是相互独立的；<br>而 SharedWorker 提供了能力能够让不同标签中页面共享的同一个 Worker 脚本线程；<br>当然，有个很重要的限制就是它们需要满足同源策略，也就是需要在同域下；<br>在页面（可以多个）中实例化 Worker 线程：</p>
<h3 id="3-2-浏览器兼容性"><a href="#3-2-浏览器兼容性" class="headerlink" title="3.2. 浏览器兼容性"></a>3.2. 浏览器兼容性</h3><p><a href="https://caniuse.com/#search=sharedWorker" target="_blank" rel="noopener">sharedWorker 浏览器兼容性</a></p>
<h3 id="3-3-简单实例"><a href="#3-3-简单实例" class="headerlink" title="3.3. 简单实例"></a>3.3. 简单实例</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// main.js</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> myWorker = <span class="keyword">new</span> SharedWorker(<span class="string">"worker.js"</span>);</span><br><span class="line"></span><br><span class="line">myWorker.port.start();</span><br><span class="line"></span><br><span class="line">myWorker.port.postMessage(<span class="string">"hello, I'm main"</span>);</span><br><span class="line"></span><br><span class="line">myWorker.port.onmessage = <span class="function"><span class="keyword">function</span>(<span class="params">e</span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'Message received from worker'</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// worker.js</span></span><br><span class="line">onconnect = <span class="function"><span class="keyword">function</span>(<span class="params">e</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> port = e.ports[<span class="number">0</span>];</span><br><span class="line"></span><br><span class="line">  port.addEventListener(<span class="string">'message'</span>, <span class="function"><span class="keyword">function</span>(<span class="params">e</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> workerResult = <span class="string">'Result: '</span> + (e.data[<span class="number">0</span>]);</span><br><span class="line">    port.postMessage(workerResult);</span><br><span class="line">  &#125;);</span><br><span class="line">  port.start();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="4-环境与作用域"><a href="#4-环境与作用域" class="headerlink" title="4. 环境与作用域"></a>4. 环境与作用域</h2><p>在 Worker 线程的运行环境中没有 <code>window</code> 全局对象，也无法访问 <code>DOM</code> 对象，所以一般来说他只能来执行纯 JavaScript 的计算操作。但是，他还是可以获取到部分浏览器提供的 API 的：</p>
<p><code>setTimeout()</code>， <code>clearTimeout()</code>， <code>setInterval()</code>，<code>clearInterval()</code>：有了这些函数，就可以在 Worker : 线程中可以再创建 worker；<code>XMLHttpRequest</code> 对象：意味着我们可以在 Worker 线程中执行 <code>ajax</code> 请求；<code>navigator</code> 对象：可以获取到 <code>AppName</code>，<code>appVersion</code>，<code>platform</code>，<code>userAgent</code> 等信息；<code>location</code> 对象（只读）：可以获取到有关当前 URL 的信息；<code>Application Cache</code>、<code>indexedDB</code>、<code>WebSocket</code>、<code>Promise</code>。</p>
<h2 id="5-库或外部脚本引入和访问"><a href="#5-库或外部脚本引入和访问" class="headerlink" title="5. 库或外部脚本引入和访问"></a>5. 库或外部脚本引入和访问</h2><p>在线程中，提供了 <code>importScripts</code> 方法，如果线程中使用了 <code>importScripts</code> 一般按照以下步骤解析。</p>
<ol>
<li>解析 <code>importScripts</code> 方法的每一个参数</li>
<li>如果有任何失败或者错误，抛出 <code>SYNTAX_ERR</code> 异常</li>
<li>尝试从用户提供的 URL 资源位置处获取脚本资源</li>
<li>对于 <code>importScripts</code> 方法的每一个参数，按照用户的提供顺序，获取脚本资源后继续进行其它操作</li>
</ol>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// worker.js</span></span><br><span class="line">importScripts(<span class="string">'math_utilities.js'</span>);</span><br><span class="line">onmessage = <span class="function"><span class="keyword">function</span> (<span class="params">event</span>)</span></span><br><span class="line"><span class="function"> </span>&#123;</span><br><span class="line">     <span class="keyword">var</span> first=event.data.first;</span><br><span class="line">     <span class="keyword">var</span> second=event.data.second;</span><br><span class="line">     calculate(first,second); <span class="comment">// calculate 是math_utilities.js中的方法</span></span><br><span class="line"> &#125;;</span><br></pre></td></tr></table></figure>
<p>也可以一次性引入多个脚本：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//可以多起一次传入</span></span><br><span class="line">importScripts(<span class="string">'script1.js'</span>, <span class="string">'script2.js'</span>);</span><br></pre></td></tr></table></figure>
<h2 id="6-通讯原理"><a href="#6-通讯原理" class="headerlink" title="6. 通讯原理"></a>6. 通讯原理</h2><p>从一个线程到另一个线程的通讯实际上是一个值拷贝的过程，实际上是先将数据<code>JSON.stringify</code>之后再<code>JSON.parse</code>。主线程与子线程之间也可以交换二进制数据，比如<code>File</code>、<code>Blob</code>、<code>ArrayBuffer</code>等对象，也可以在线程之间发送。但是，用拷贝方式发送二进制数据，会造成性能问题。比如，主线程向子线程发送一个 50MB 文件，默认情况下浏览器会生成一个原文件的拷贝。为了解决这个问题，JavaScript 允许主线程把二进制数据直接转移给子线程，转移后主线程无法再使用这些数据，这是为了防止出现多个线程同时修改数据的问题，这种转移数据的方法，叫做<code>Transferable Objects</code>。</p>
<p>不过现在很多浏览器支持<code>transferable objects</code>(可转让对象) ,这个技术是零拷贝转移，能大大提升性能，可以指定传送的数据全都是零拷贝。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">var abBuffer = new ArrayBuffer(32);</span><br><span class="line">aDedicatedWorker.postMessage(abBuffer, [abBuffer]);</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">var objData = &#123;</span><br><span class="line">   &quot;employeeId&quot;: 103,</span><br><span class="line">   &quot;name&quot;: &quot;Sam Smith&quot;,</span><br><span class="line">   &quot;dateHired&quot;: new Date(2006, 11, 15),</span><br><span class="line">   &quot;abBuffer&quot;: new ArrayBuffer(32)</span><br><span class="line">&#125;;</span><br><span class="line">aDedicatedWorker.postMessage(objData, [objData.abBuffer]);</span><br></pre></td></tr></table></figure>
<h2 id="7-应用场景"><a href="#7-应用场景" class="headerlink" title="7. 应用场景"></a>7. 应用场景</h2><ol>
<li><strong>使用专用线程进行数学运算</strong><br>Web Worker 最简单的应用就是用来做后台计算，而这种计算并不会中断前台用户的操作</li>
<li><strong>图像处理</strong><br>通过使用从 <code>&lt;canvas&gt;</code> 或者 <code>&lt;video&gt;</code> 元素中获取的数据，可以把图像分割成几个不同的区域并且把它们推送给并行的不同 Workers 来做计算</li>
<li><strong>大量数据的检索</strong><br>当需要在调用 <code>ajax</code> 后处理大量的数据，如果处理这些数据所需的时间长短非常重要，可以在 Web Worker 中来做这些，避免冻结 UI 线程</li>
<li><strong>背景数据分析</strong><br>由于在使用 Web Worker 的时候，我们有更多潜在的 CPU 可用时间，我们现在可以考虑一下 JavaScript 中的新应用场景。例如，我们可以想像在不影响 UI 体验的情况下实时处理用户输入。利用这样一种可能，我们可以想像一个像 Word（Office Web Apps 套装）一样的应用：当用户打字时后台在词典中进行查找，帮助用户自动纠错等等</li>
</ol>
<h2 id="8-限制"><a href="#8-限制" class="headerlink" title="8. 限制"></a>8. 限制</h2><ol>
<li>兼容性</li>
<li>不能访问 <code>DOM</code> 和 <code>BOM</code> 对象，<code>location</code> 和 <code>navigator</code> 的只读访问，并且 <code>navigator</code> 封装成了 <code>WorkerNavigator</code> 对象，更改部分属性。无法读取本地文件系统</li>
<li>子线程和父级线程的通讯是通过值拷贝，子线程对通信内容的修改，不会影响到主线程。在通讯过程中值过大也会影响到性能（解决这个问题可以用<code>transferable objects</code>）</li>
<li>并非真的多线程，多线程是因为浏览器的功能</li>
<li>条数限制，大多浏览器能创建 webWorker 线程的条数是有限制的，虽然可以手动去拓展，但是如果不设置的话，基本上都在20条以内，每条线程大概5M左右，需要手动关掉一些不用的线程才能够创建新的线程</li>
</ol>
<h2 id="9-优秀开源框架"><a href="#9-优秀开源框架" class="headerlink" title="9. 优秀开源框架"></a>9. 优秀开源框架</h2><p><a href="https://github.com/DoubleSpout/node-threads-a-gogo2" target="_blank" rel="noopener">tagg2</a></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/06/01/HTML5-SSE/" rel="next" title="HTML5 之 Server-Sent Events™">
                <i class="fa fa-chevron-left"></i> HTML5 之 Server-Sent Events™
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/06/01/HTML5-ApplicationCache/" rel="prev" title="HTML5 之 Application Cache™">
                HTML5 之 Application Cache™ <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/blog/images/avatar.jpg"
               alt="曦瓜皮" />
          <p class="site-author-name" itemprop="name">曦瓜皮</p>
           
              <p class="site-description motion-element" itemprop="description"></p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/blog/archives/">
                <span class="site-state-item-count">15</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/blog/categories/index.html">
                <span class="site-state-item-count">6</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        

      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-Web-Worker-简介"><span class="nav-number">1.</span> <span class="nav-text">1. Web Worker 简介</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-1-什么是-Web-Worker"><span class="nav-number">1.1.</span> <span class="nav-text">1.1. 什么是 Web Worker</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-2-Web-Worker-问世背景"><span class="nav-number">1.2.</span> <span class="nav-text">1.2. Web Worker 问世背景</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-3-Web-Worker-类型"><span class="nav-number">1.3.</span> <span class="nav-text">1.3. Web Worker 类型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-4-浏览器兼容性"><span class="nav-number">1.4.</span> <span class="nav-text">1.4. 浏览器兼容性</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-使用方法"><span class="nav-number">2.</span> <span class="nav-text">2. 使用方法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2-1-创建-Web-Worker"><span class="nav-number">2.1.</span> <span class="nav-text">2.1. 创建 Web Worker</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-2-事件监听"><span class="nav-number">2.2.</span> <span class="nav-text">2.2. 事件监听</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-3-终止-Web-Worker"><span class="nav-number">2.3.</span> <span class="nav-text">2.3. 终止 Web Worker</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-4-错误机制"><span class="nav-number">2.4.</span> <span class="nav-text">2.4. 错误机制</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-5-简单实例"><span class="nav-number">2.5.</span> <span class="nav-text">2.5. 简单实例</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#2-5-1-webWork-html"><span class="nav-number">2.5.1.</span> <span class="nav-text">2.5.1 webWork.html</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-5-2-webWork-js"><span class="nav-number">2.5.2.</span> <span class="nav-text">2.5.2 webWork.js</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-sharedWorker"><span class="nav-number">3.</span> <span class="nav-text">3. sharedWorker</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#3-1-sharedWorker-介绍"><span class="nav-number">3.1.</span> <span class="nav-text">3.1. sharedWorker 介绍</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-2-浏览器兼容性"><span class="nav-number">3.2.</span> <span class="nav-text">3.2. 浏览器兼容性</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-3-简单实例"><span class="nav-number">3.3.</span> <span class="nav-text">3.3. 简单实例</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-环境与作用域"><span class="nav-number">4.</span> <span class="nav-text">4. 环境与作用域</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-库或外部脚本引入和访问"><span class="nav-number">5.</span> <span class="nav-text">5. 库或外部脚本引入和访问</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#6-通讯原理"><span class="nav-number">6.</span> <span class="nav-text">6. 通讯原理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#7-应用场景"><span class="nav-number">7.</span> <span class="nav-text">7. 应用场景</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#8-限制"><span class="nav-number">8.</span> <span class="nav-text">8. 限制</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#9-优秀开源框架"><span class="nav-number">9.</span> <span class="nav-text">9. 优秀开源框架</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">曦瓜皮</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Muse
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.2"></script>



  
  

  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.2"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.2"></script>



  


  




	





  





  






  





  

  

  

  

  

  

</body>
</html>
